package bim.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import bim.domain.Role;
import bim.domain.User;

	public class UserDaoImpl extends JdbcDaoSupport implements UserDao {

	@Override
	public User findByName(String name) {
		String sql = 
				"SELECT U.ID,U.NAME,U.PASSWD,U.FULL_NAME,R.ID AS ROLE_ID, R.NAME AS ROLE_NAME "
				+ "FROM USER U,ROLE R "
				+ "WHERE U.NAME = ?  AND U.ROLE_ID = R.ID";
		String sql_cnt =  "SELECT count(1)  FROM USER U,ROLE R  WHERE U.NAME = ?  AND U.ROLE_ID = R.ID";
		int count = getJdbcTemplate().queryForObject(sql_cnt, new Object[] { name }, Integer.class);
		User user = new User();
		if(count==1){
			user = (User)getJdbcTemplate().queryForObject(
				sql, new Object[] { name }, new UserRowMapper());
		}
		return user;
	}
	
	private class UserRowMapper implements RowMapper{
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			User user = new User();
			user.setId(rs.getString("ID"));
			user.setName(rs.getString("NAME"));
			user.setPassword(rs.getString("PASSWD"));
			
			Role role = new Role();
			role.setId(rs.getString("role_id"));
			role.setName(rs.getString("role_name"));
			List roleList = new ArrayList();
			roleList.add(role);
			user.setRoleList(roleList);
	
			return user;
		}
	}

}